package com.softeem.dromitorysystem.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softeem.dromitorysystem.dto.Result;
import com.softeem.dromitorysystem.entity.Manager;
import com.softeem.dromitorysystem.mapper.ManagerMapper;
import com.softeem.dromitorysystem.service.ManagerService;
import org.springframework.stereotype.Service;

import java.util.Objects;

//业务实现
@Service
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements ManagerService {
    @Override
    public Result login(Manager manager) {
        //根据用户名查询用户是否存在
        //创建查询条件构造器(select * from manager where username=XXX)
        QueryWrapper<Manager> query = Wrappers.query(Manager.class);
        query.eq("username",manager.getUsername());
        //根据给定的条件构造器查询对象
        Manager m = getOne(query);
        if(Objects.isNull(m)){
            //链式编程
            return Result.fail().setMsg("用户不存在");
        }
        if(m.getStatus() !=0){
            return Result.fail().setMsg("账号禁用").setCode(1);
        }

        //将数据库中用户的盐取出并与用户输入的密码组合
        String pwd = SecureUtil.md5(m.getSalt() + manager.getPassword());
        manager.setPassword(pwd);

        if(Objects.equals(m.getPassword(),manager.getPassword())){
            return Result.ok().setMsg("登陆成功").setData(m);
        }
        return Result.fail().setMsg("密码错误").setCode(0);
    }

    @Override
    public Result reg(Manager manager) {
        //添加注册(先查询)
        QueryWrapper<Manager> query =Wrappers.query(Manager.class);
        query.eq("username",manager.getUsername());
        //根据给定的条件构造器查询对象
        Manager m = getOne(query);
        if(Objects.nonNull(m)){
            System.out.println("该账号已存在");
        }

        //生成一个随机盐
        String salt = RandomUtil.randomString(6);
        manager.setSalt(salt);
        //随机盐和输入的密码组合加密
        String pwd = salt + manager.getPassword();
        //使用MD5对组合后的密码加密
        pwd = SecureUtil.md5(pwd);
        //填充加密后的密码到对象中
        manager.setPassword(pwd);

        //执行添加 并判断
        if (save(manager)){
            return Result.ok().setMsg("添加成功").setData(manager);
        }
        return Result.fail().setMsg("添加失败").setCode(1);
    }
}
